package com.meepo.feed.video.fullscreen

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.meepo.basic.components.view.MeepoFragment
import com.meepo.basic.schema.common.PageResult
import com.meepo.feed.R
import com.meepo.feed.video.fullscreen.cache.PreloadManager
import com.meepo.feed.video.fullscreen.cache.ProxyVideoCacheManager
import com.meepo.feed.video.fullscreen.widget.TikTokRenderViewFactory
import com.meepo.feed.video.fullscreen.widget.VerticalViewPager
import com.meepo.basic.schema.feed.Item
import com.meepo.feed.API
import com.meepo.feed.API.Companion.FeedCategory_Video
import com.xiaojinzi.component.support.ParameterSupport
import kotlinx.android.synthetic.main.video_mini_list_fragment.*
import xyz.doikki.videoplayer.ijk.IjkPlayer
import xyz.doikki.videoplayer.player.VideoView

class FullSnVideoFragment : MeepoFragment() {
    /**
     * 当前播放位置
     */
    private var mCurPos = 0
    private val mVideoList: ArrayList<Item> = ArrayList()
    private lateinit var mFullSnVideoAdapter: FullSnVideoAdapter
    private var mVideoView: VideoView<IjkPlayer>? = null

    private lateinit var mController: FullSnVideoController

    fun refresh(rsp: PageResult<Item>?) {
        rsp?.items?.let {
            addData(it)

            vertical_view_pager.currentItem = 0
            vertical_view_pager.post { startToPlay(0) }
        }
    }

    fun append(rsp: PageResult<Item>?) {
        rsp?.items?.let {
            addData(it)
        }
    }

    private fun addData(items: List<Item>) {
//        mVideoList.addAll(DataUtil.getTiktokDataFromAssets(this.requireContext()))
        mVideoList.addAll(items)
        mFullSnVideoAdapter.notifyDataSetChanged()
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        initVideoView()
        initViewPager()
    }

    private fun initVideoView() {
        mVideoView = VideoView(this.requireContext())
        mVideoView?.setLooping(true)

        //以下只能二选一，看你的需求
        mVideoView?.setRenderViewFactory(TikTokRenderViewFactory.create())
        //        mVideoView?.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
        mController = FullSnVideoController(this.requireContext())
        mVideoView?.setVideoController(mController)
    }


    private fun initViewPager() {
        vertical_view_pager.offscreenPageLimit = 4
        mFullSnVideoAdapter = FullSnVideoAdapter(mVideoList)
        vertical_view_pager.adapter = mFullSnVideoAdapter
        vertical_view_pager.overScrollMode = View.OVER_SCROLL_NEVER
        vertical_view_pager.setOnPageChangeListener(object : SimpleOnPageChangeListener() {
            private var mCurItem = 0

            /**
             * VerticalViewPager是否反向滑动
             */
            private var mIsReverseScroll = false
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                if (position == mCurItem) {
                    return
                }
                mIsReverseScroll = position < mCurItem
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)

                Log.e(
                    "onPageSelected",
                    "mIsReverseScroll: $mIsReverseScroll  mVideoList.size: ${mVideoList.size}  pos: $position mCurPos: $mCurPos"
                )

                if ((mVideoList.size == 0) || position >= mCurItem && mVideoList.size - position - 1 < 5) {

                    presenter.call(
                        API.instance().fetchFeedItemsV2(category = FeedCategory_Video),
                        { rsp -> append(rsp.data) }
                    )
                }

                if (position == mCurPos) return
                startToPlay(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = vertical_view_pager.currentItem
                }
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
                    PreloadManager.instance(requireContext()).resumePreload(mCurPos, mIsReverseScroll)
                } else {
                    PreloadManager.instance(requireContext()).pausePreload(mCurPos, mIsReverseScroll)
                }
            }
        })
    }

    private fun startToPlay(position: Int) {
        val count = vertical_view_pager.childCount

        for (i in 0 until count) {
            val itemView = vertical_view_pager.getChildAt(i)
            val viewHolder = itemView.tag as FullSnVideoAdapter.VideoViewHolder
            if (viewHolder.mPosition == position) {
                mVideoView?.release()
                Utils.removeViewFormParent(mVideoView)
                val tiktokBean = mVideoList[position]
                val playUrl = PreloadManager.instance(requireContext()).getLocalPlayUrl(tiktokBean.content?.content)
                mVideoView?.setUrl(playUrl)
                mController.addControlComponent(viewHolder.mFullSnVideoView, true)
                viewHolder.mPlayerContainer.addView(mVideoView, 0)
                mVideoView?.start()

                mCurPos = position
                break
            }
        }
    }


    // 页面切换事件
    override fun onHiddenChanged(hidden: Boolean) {

        Log.d("onHiddenChanged", "" + hidden)
        super.onHiddenChanged(hidden)
        if (hidden) {
            mVideoView?.pause()
        } else {
            mVideoView?.resume()
        }
    }

    fun pauseCurrentIfExists() {
        mVideoView?.pause()
    }

    fun resumeCurrentIfExistsAndVisible() {

        if (mVisible) {
            mVideoView?.resume()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        PreloadManager.instance(requireContext()).removeAllPreloadTask()
        //清除缓存，实际使用可以不需要清除，这里为了方便测试
        ProxyVideoCacheManager.clearAllCache(this.requireContext())
    }

    override fun initData() {
        ParameterSupport.getSerializable<ArrayList<Item>>(arguments, "videoList")?.let {
            addData(it)
        }

        presenter.call(
            API.instance().fetchFeedItemsV2(category = FeedCategory_Video),
            { rsp -> refresh(rsp.data) }
        )
    }

    override fun setUpContentLayout(): Int = R.layout.video_mini_list_fragment


    companion object {

        fun instance(videoList: ArrayList<Item>? = arrayListOf()): FullSnVideoFragment {
            val rsp = FullSnVideoFragment()
            val bundle = Bundle()
            videoList?.let { bundle.putSerializable("videoList", videoList) }
            rsp.arguments = bundle
            return rsp
        }
    }
}